package com.tydic.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.EnableEnum;
import com.tydic.common.core.enums.MessageCategoryEnum;
import com.tydic.common.core.enums.UserTypeEnum;
import com.tydic.common.core.utils.StringUtils;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.system.domain.SysMessage;
import com.tydic.system.domain.SysUser;
import com.tydic.system.domain.bo.QuerySysMessageBo;
import com.tydic.system.mapper.SysMessageMapper;
import com.tydic.system.service.ISysMessageService;
import com.tydic.system.service.ISysUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Slf4j
@Service
public class SysMessageServiceImpl implements ISysMessageService {

    private final SysMessageMapper sysMessageMapper;

    private final ISysUserService sysUserService;

    @Override
    public Page<SysMessage> selectPage(QuerySysMessageBo bo) {
        LambdaQueryWrapper<SysMessage> lqw = buildQueryWrapper(bo);
        return sysMessageMapper.selectPage(bo.build(), lqw);
    }

    private LambdaQueryWrapper<SysMessage> buildQueryWrapper(QuerySysMessageBo bo) {
        LambdaQueryWrapper<SysMessage> lqw = Wrappers.lambdaQuery(SysMessage.class);
        lqw.eq(StringUtils.isNotBlank(bo.getCategory()), SysMessage::getCategory, bo.getCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getReceiver()), SysMessage::getReceiver, bo.getReceiver());
        return lqw;
    }

    /**
     * 处理平台的代办信息
     *
     * @param category
     * @param categoryId
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertNeedHandler(MessageCategoryEnum category, String categoryId, String title, String msg) {
        List<SysUser> userList = getPlatformUsers();
        userList.forEach(item -> insertMessage(category, categoryId, title, msg, item.getUserCode()));
    }

    /**
     * 插入单条
     *
     * @param category
     * @param categoryId
     * @param title
     * @param msg
     * @param receiver
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertMessageHandler(MessageCategoryEnum category, String categoryId, String title, String msg, String receiver) {
        insertMessage(category, categoryId, title, msg, receiver);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertMessage(MessageCategoryEnum category, String categoryId, String title, String msg, String receiver) {
        SysMessage message = new SysMessage();
        message.setMessage(msg);
        message.setTitle(title);
        message.setCategoryId(categoryId);
        message.setReceiver(receiver);
        message.setCategory(category.getStatus());
        message.setViewStatus(EnableEnum.DISABLE.getStatus());
        sysMessageMapper.insert(message);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void handleMessage(MessageCategoryEnum category, String categoryId) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        if (currentUser == null) {
            return;
        }
        String userType = currentUser.getUserType();
        if (StrUtil.equalsAny(userType, UserTypeEnum.PLATFORM.getUserType(), UserTypeEnum.ADMIN.getUserType(), UserTypeEnum.ROOT.getUserType())) {
            List<String> receivers = getPlatformUsers().stream().map(SysUser::getUserCode).collect(Collectors.toList());
            if (CollUtil.isEmpty(receivers)) {
                return;
            }
            for (String receiver : receivers) {
                completeMessage(category, categoryId, receiver);
            }
        } else {
            completeMessage(category, categoryId, currentUser.getUserCode());
        }
    }

    /**
     * 处理签署的代办信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void completeMessage(MessageCategoryEnum category, String categoryId, String receiver) {
        // 标志为已读
        List<SysMessage> messages = sysMessageMapper.selectList(Wrappers.lambdaQuery(SysMessage.class).eq(SysMessage::getCategoryId, categoryId).eq(SysMessage::getCategory, category.getStatus()).eq(SysMessage::getReceiver, receiver));
        if (CollUtil.isNotEmpty(messages)) {
            for (SysMessage item : messages) {
                item.setViewStatus(EnableEnum.ENABLE.getStatus());
                sysMessageMapper.updateById(item);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void completeMessage(MessageCategoryEnum category, String categoryId) {
        // 标志为已读
        List<SysMessage> messages = sysMessageMapper.selectList(Wrappers.lambdaQuery(SysMessage.class).eq(SysMessage::getCategoryId, categoryId).eq(SysMessage::getCategory, category.getStatus()));
        if (CollUtil.isNotEmpty(messages)) {
            for (SysMessage item : messages) {
                item.setViewStatus(EnableEnum.ENABLE.getStatus());
                sysMessageMapper.updateById(item);
            }
        }
    }

    @Override
    public SysMessage getMessage(MessageCategoryEnum category, String categoryId, String receiver) {
        return sysMessageMapper.selectOne(Wrappers.lambdaQuery(SysMessage.class).eq(SysMessage::getCategoryId, categoryId).eq(SysMessage::getCategory, category.getStatus()).eq(SysMessage::getReceiver, receiver), false);
    }

    private List<SysUser> getPlatformUsers() {
        String[] userTypes = new String[]{UserTypeEnum.PLATFORM.getUserType(), UserTypeEnum.ROOT.getUserType(), UserTypeEnum.ADMIN.getUserType()};
        return sysUserService.getUsersByUserTypes(userTypes);
    }
}
